﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common.Tool.FileTools
{
    public class ConfigHelper
    {
        /// <summary>
        /// 读取exe.config文件所有Key
        /// </summary>
        /// <returns></returns>
        public static Dictionary<string, string> ReadAll()
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            foreach (string key in config.AppSettings.Settings.AllKeys)
            {
                dic[key] = config.AppSettings.Settings[key].Value;
            }
            return dic;
        }
        /// <summary>
        /// 写入exe.config文件
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void Write(string key, string value)
        {

            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (config.AppSettings.Settings[key] == null)
            {
                config.AppSettings.Settings.Add(key, value);
            }
            else
            {
                config.AppSettings.Settings[key].Value = value;
            }
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");//   重新加载新的配置文件   
        }
    }
}
